package com.usdt.common.utils.bean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.ContextLoader;

public class BeanUtil extends BeanUtils {

	private static final Logger logger = LoggerFactory.getLogger(BeanUtil.class);

	public volatile static ApplicationContext context;
	private static Object lockContext = new Object();

	public static <T> T toBean(Object source, Class<T> clazz) {
		if (ObjectUtils.isEmpty(source))
			return null;

		T target = instantiateClass(clazz);
		copyProperties(source, target);
		return target;
	}

	public static <S, T> List<T> toBeans(List<S> sources, Class<T> clazz) {
		if (CollectionUtils.isEmpty(sources))
			return Collections.emptyList();

		List<T> beans = new ArrayList<>();
		for (S source : sources) {
			T bean = instantiateClass(clazz);
			copyProperties(source, bean);
			beans.add(bean);
		}

		return beans;
	}

	/**
	 * 非注解方式获取bean
	 * 
	 * @param beanName
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(String beanName, Class<T> clazz) {
		try {
			init();

			return context.getBean(beanName, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 非注解方式获取bean
	 * 
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz) {
		try {
			init();

			return context.getBean(clazz);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void init() {

		if (context == null) {
			synchronized (lockContext) {
				if (context == null) {
					try {
						context = ContextLoader.getCurrentWebApplicationContext();
					} catch (Exception e) {
						logger.info("context no init");
					}
				}
			}
		}
	}
}